<template>
    <div class="user-manage">
        <el-card>
            <template #header>
                <div class="header-bar">
                    <span>用户管理</span>
                    <div>
                        <el-button type="primary" size="small" @click="onAddUser">新增用户</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="tableData" border style="width: 100%; margin-bottom: 16px;" :loading="loading">
                <el-table-column prop="avatarUrl" label="头像" min-width="80">
                    <template #default="{ row }">
                        <el-avatar :src="row.avatarUrl" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="nickname" label="昵称" min-width="120">
                    <template #default="{ row }">
                        <span :class="{ 'no-data': !row.nickname }">{{ row.nickname || '暂无' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" min-width="120" />
                <el-table-column prop="email" label="邮箱" min-width="180">
                    <template #default="{ row }">
                        <span :class="{ 'no-data': !row.email }">{{ row.email || '暂无' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" min-width="120">
                    <template #default="{ row }">
                        <span :class="{ 'no-data': !row.phone }">{{ row.phone || '暂无' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="rolesName" label="角色" min-width="120">
                    <template #default="{ row }">
                        <template v-if="row.rolesName && row.rolesName.length">
                            <el-tag v-for="role in row.rolesName" :key="role"
                                :type="roleStatusMap[role] === false ? 'info' : 'success'"
                                :color="roleStatusMap[role] === false ? '#f4f4f5' : ''"
                                :style="roleStatusMap[role] === false ? { color: '#b1b3b8', 'border-color': '#ebeef5', position: 'relative' } : {}"
                                class="role-tag">
                                <span style="position: relative; display: inline-block;">
                                    <span v-if="roleStatusMap[role] === false"
                                        style="color: #f56c6c; font-size: 20px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 2; pointer-events: none;"
                                        title="该角色已禁用">×</span>
                                    <span style="position: relative; z-index: 1;">{{ role }}</span>
                                </span>
                            </el-tag>
                        </template>
                        <span v-else class="no-role">无角色</span>
                    </template>
                </el-table-column>
                <el-table-column prop="isActived" label="状态" min-width="80">
                    <template #default="{ row }">
                        <el-tooltip :content="row.isActived ? '点击禁用' : '点击激活'" placement="top">
                            <el-tag :type="row.isActived ? 'success' : 'warning'" style="cursor: pointer"
                                @click="onToggleStatus(row)">
                                {{ row.isActived ? '已激活' : '未激活' }}
                            </el-tag>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="160">
                    <template #default>
                        <el-button type="primary" size="small" disabled>编辑</el-button>
                        <el-button type="danger" size="small" disabled>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-bar">
                <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-size="pageSize" :current-page="pageIndex" :page-sizes="[5, 10, 20, 50, 100]"
                    @size-change="handleSizeChange" @current-change="handlePageChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { userApi } from '../api/user'
import { ElMessage } from 'element-plus'
import { roleApi } from '../api/role'
const roleStatusMap = ref({})
async function fetchRoleStatus() {
    const res = await roleApi.getRoles(1, 1000)
    if (res.data.code === 1000) {
        roleStatusMap.value = Object.fromEntries(
            res.data.data.items.map(role => [role.roleName, role.isActived])
        )
    }
}

const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(10)
const loading = ref(false)

async function fetchData() {
    loading.value = true
    try {
        const res = await userApi.getUsers(pageIndex.value, pageSize.value)
        if (res.data.code === 1000) {
            tableData.value = res.data.data.items
            total.value = res.data.data.totalCount
        } else {
            ElMessage.error(res.data.msg || '获取用户数据失败')
        }
    } catch {
        ElMessage.error('获取用户数据失败')
    } finally {
        loading.value = false
    }
}

function handleSizeChange(val) {
    pageSize.value = val
    pageIndex.value = 1
    fetchData()
}

function handlePageChange(val) {
    pageIndex.value = val
    fetchData()
}

function onAddUser() {
    ElMessage.info('新增用户功能待实现')
}

async function onToggleStatus(row) {
    try {
        let res
        if (row.isActived) {
            res = await userApi.disableUser(row.id)
        } else {
            res = await userApi.enableUser(row.id)
        }
        if (res.data.code === 1000) {
            ElMessage.success(res.data.msg || '操作成功')
            fetchData()
        } else {
            ElMessage.error(res.data.msg || '操作失败')
        }
    } catch {
        ElMessage.error('操作失败')
    }
}

// 监听头像更新事件
const handleAvatarUpdated = () => {
    fetchData()
}

onMounted(() => {
    fetchRoleStatus()
    fetchData()
    // 添加事件监听器
    window.addEventListener('avatar-updated', handleAvatarUpdated)
})

onUnmounted(() => {
    // 移除事件监听器
    window.removeEventListener('avatar-updated', handleAvatarUpdated)
})
</script>

<style scoped>
.user-manage {
    max-width: 1200px;
    margin: 20px auto;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.role-tag {
    margin-right: 4px;
}

.no-role {
    color: #c0c4cc;
    font-style: italic;
}

.no-data {
    color: #c0c4cc;
    font-style: italic;
}

.pagination-bar {
    margin-top: 16px;
    text-align: right;
}
</style>